﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ScheduleMaker.DB;
using ScheduleMaker.DB.CoreDAO;
using ScheduleMaker.DB.Domain;
using ScheduleMaker.DB.Domain.Core;
using ScheduleMaker.ConfigManager;

namespace ScheduleMaker
{
    public partial class smTeacherForm : Form
    {

        const int MAX_NUMBER_OF_SUBJECTS = 50;

        const int columnMinimumWidth = 190;
       
        // Dni tygodnia.
        IList<DB.Domain.Core.Day> days;
        IList<Group> groups;
        IList<Category> categories;
        IList<Classroom> classrooms;
        IList<Teacher> teachers;
        IList<Hour> hours;
        IList<ClassHour> classHours;

        Color[] colors;

        Mode mode;


        public smTeacherForm()
        {
            Cursor = Cursors.WaitCursor;

            InitializeComponent();

            if (ConfigManager.ConfigManager.isConfigLoaded())
            {
                mode = ConfigManager.ConfigManager.getConfiguration().Type;
            }

            if(mode == Mode.School)
            {
                this.Text = "ScheduleMaker - Panel Prowadzącego - TRYB: SZKOŁA";
            }
            else
            {
                this.labelGroup.Text = "Blok:";
                this.Text = "ScheduleMaker - Panel Prowadzącego - TRYB: UCZELNIA";
            }

            grid.Rows.Clear();
            grid.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            grid.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            loadDays();
            loadClassHours();
            loadGroupsOrCategories();
            loadTeachers();
            loadClassrooms();

            // Przygotowanie grida preferencji.
            gridPref.Rows.Clear();
            gridPref.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            gridPref.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
            gridPref.ReadOnly = true;
            gridPref.MultiSelect = false;
            gridPref.AllowUserToAddRows = false;
           

            fillHours();

            // do przeniesienia
                gridAntypref.Rows.Clear();
                gridAntypref.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
                gridAntypref.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft;
                gridAntypref.ReadOnly = true;
                gridAntypref.AllowUserToAddRows = false;
                gridAntypref.ColumnCount = 3;
                gridAntypref.Columns[0].Name = "Prowadzący";
                gridAntypref.Columns[0].MinimumWidth = 150;
                gridAntypref.Columns[1].Name = "Od:";
                gridAntypref.Columns[1].MinimumWidth = 150;
                gridAntypref.Columns[2].Name = "Do:";
                gridAntypref.Columns[2].MinimumWidth = 150;
                dtpickFrom.Format = dtpickTo.Format = DateTimePickerFormat.Custom;
                dtpickFrom.CustomFormat = dtpickTo.CustomFormat = "dd-MM-yyyy HH:mm";
            //

                colors = new Color[] {
                Color.DarkOrange ,
                Color.Yellow ,
                Color.DeepSkyBlue ,
                Color.Violet ,
                Color.LightGreen ,
                Color.Chocolate ,
                Color.DarkGray ,
                Color.LimeGreen ,
                Color.MediumAquamarine ,
                Color.DarkTurquoise ,
                Color.Goldenrod ,
                Color.LightBlue ,
                Color.MediumOrchid ,
                Color.Gold ,
                Color.Tomato ,
                Color.HotPink ,
                Color.Orange ,
                Color.GreenYellow ,
                Color.Magenta ,
                Color.Orchid ,
                Color.RosyBrown ,
                Color.Chartreuse ,
            };

            Cursor = Cursors.Default;

        }


        private void loadDays()
        {
            // Wczytanie dni tygodnia.
            DayDAO dao = DAOFactory.getDayDAO(mode);
            days = dao.getAll();

            grid.ColumnCount = days.Count;
            int i = 0;
            foreach (var day in days)
            {
                grid.Columns[i].Name = day.Name;
                grid.Columns[i].MinimumWidth = columnMinimumWidth;
                i++;
            }

            foreach (var day in days)
            {
                comboBoxDays.Items.Add(day.Name);
            }
            comboBoxDays.SelectedIndex = 0;
            comboBoxDays.DropDownStyle= ComboBoxStyle.DropDownList;
        }

        private void loadClassHours()
        {
            grid.RowHeadersWidth = 200;

            ClassHourDAO classHourDAO = DAOFactory.getClassHourDAO(mode);
            classHours = classHourDAO.getAll();

            int i = 0;
            foreach (var classHour in classHours)
            {
                string[] rowValues = { };
                grid.Rows.Add(rowValues);
                grid.Rows[i++].HeaderCell.Value =
                    classHour.Begin.ToString().Substring(0, 5) +
                    " - " +
                    classHour.End.ToString().Substring(0, 5)
                ;
            }

        }


        private void loadGroupsOrCategories()
        {
            if (mode == Mode.School)
            {
                GroupDAO groupDAO = DAOFactory.getGroupDAO(mode);
                groups = groupDAO.getAll();
                foreach (var elem in groups)
                {
                    comboBoxGroups.Items.Add(elem.Id + " - " + elem.Name);
                }
                comboBoxGroups.DropDownStyle = ComboBoxStyle.DropDownList;
            }
            else
            {
                CategoryDAO categoryDAO = DAOFactory.getCategoryDAO(mode);
                categories = categoryDAO.getAll();
                foreach (var category in categories)
                {
                    comboBoxGroups.Items.Add(category.Id + " - " + category.Name);
                }
                comboBoxGroups.DropDownStyle = ComboBoxStyle.DropDownList;
            }
        }

        private void loadClassrooms()
        {
            ClassroomDAO classroomDAO = DAOFactory.getClassroomDAO(mode);
            classrooms = classroomDAO.getAll();
            foreach (var elem in classrooms)
            {
                comboBoxClassrooms.Items.Add(elem.Id + " - " + elem.Name);
            }
            comboBoxClassrooms.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        private void loadTeachers()
        {
            TeacherDAO teacherDAO = DAOFactory.getTeacherDAO(mode);
            teachers = teacherDAO.getAll();
            foreach (var elem in teachers)
            {
                comboBoxTeachers.Items.Add(elem.Id + " - " + elem.Name);
                // do przeniesienia
                    comboBoxTeacher.Items.Add(elem.Id + " - " + elem.Name);
                //
            }
            comboBoxTeachers.DropDownStyle = ComboBoxStyle.DropDownList;
            // do przeniesienia
                comboBoxTeacher.DropDownStyle = ComboBoxStyle.DropDownList;
                comboBoxTeacher.SelectedIndex = 0;
            //

        }

        private DB.Domain.Core.Day getDayById(int id)
        {
            foreach (var day in days)
            {
                if (day.Id == id) return day;
            }
            return null;
        }

        private void zamknijToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void add_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            HourDAO hourDao = DAOFactory.getHourDAO(mode);

            // Pobranie danych.
            Hour hour = null;
            if (mode == Mode.School)
            {
                hour = new HourSchool();
            }
            else
            {
                hour = new HourUniversity();
            }
            hour.Day = days.ElementAt(comboBoxDays.SelectedIndex);
            hour.Begin = new TimeSpan(Convert.ToInt32(hourStart.Value), Convert.ToInt32(minuteStart.Value), 0);
            hour.End = new TimeSpan(Convert.ToInt32(hourEnd.Value), Convert.ToInt32(minuteEnd.Value), 0);

            // Sprawdzenie czy prowadzący nie wprowadził już takiej preferencji.
            Boolean hourAlreadyPreferred = false;
            foreach (var preferredHour in hours)
            {
                hour.Id = preferredHour.Id;
                if (preferredHour.Equals(hour))
                {
                    MessageBox.Show("Taka preferencja już istnieje." + " ");
                    hourAlreadyPreferred = true;
                    hour.Id = 0;
                }
            }

            if (!hourAlreadyPreferred)
            {
                // Sprawdzenie czy istnieje już taki wymiar godzin.
                Boolean hourAlreadyExisting = false;
                IList<Hour> allHours = hourDao.getAll();
                foreach (var existingHour in allHours)
                {
                    hour.Id = existingHour.Id;
                    if (existingHour.Equals(hour))
                    {
                        hourAlreadyExisting = true;
                        break;
                    }
                }

                if (!hourAlreadyExisting)
                {
                    // Zapisujemy nowy wymiar godzin.
                    // Zmienna hour ma przypisane już istniejące id, ale przy save i tak jest przydzielane nowe.
                    hourDao.save(hour);
                }

                // Zapisujemy połączenie wymiaru godzin z prowadzącym.
                TeacherDAO teacherDAO = DAOFactory.getTeacherDAO(mode);
                Teacher teacher = teacherDAO.getById(Authenticator.LogedUser.Id);
                teacher.Hours.Add(hour);
                teacherDAO.update(teacher);

                fillHours();

                MessageBox.Show("Dodano preferencję.");
            }

            Cursor = Cursors.Default;
           
        }

        private void fillHours()
        {

            this.gridPref.Rows.Clear();
            TeacherDAO teacherDAO = DAOFactory.getTeacherDAO(mode);
            Teacher teacher = teacherDAO.getById(Authenticator.LogedUser.Id);  
            this.hours = teacher.Hours;
            foreach (var hour in hours)
            {
                int n = gridPref.Rows.Add();
                gridPref.Rows[n].Cells[0].Value = getDayById(hour.Day.Id).Name;
                gridPref.Rows[n].Cells[1].Value = hour.Begin;
                gridPref.Rows[n].Cells[2].Value = hour.End;
            }

        }

        private void btnTeachSettChange_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            bool valid = true;
            User user = Authenticator.LogedUser;
            UserDAO userDAO = DAOFactory.getUserDAO(mode);
            // sprawdzenie czy wpisano poprawne stare hasło
            if (valid && !MD5Coder.encode(tbTeachSettOldP.Text).Equals(user.Password))
            {
                valid = false;
                lblTeachSettWarn.ForeColor = Color.Red;
                lblTeachSettWarn.Text = "Wpisano błędne hasło.";
            }

            // sprawdzenie czy w obu polach wpisano to samo nowe hasło
            if (valid && tbTeachSettNewP.Text != tbTeachSettNewP2.Text)
            {
                valid = false;
                lblTeachSettWarn.ForeColor = Color.Red;
                lblTeachSettWarn.Text = "Wpisane hasła różnią się.";
            }

            // sprawdzenie czy cokolwiek wpisano
            // czy pozwalamy na puste hasła?
            if (valid && tbTeachSettNewP.Text == "")
            {
                valid = false;
                lblTeachSettWarn.ForeColor = Color.Red;
                lblTeachSettWarn.Text = "Nie wpisano nowego hasła.";
            }

            //minimalna długość hasła
            if (valid && tbTeachSettNewP.Text.Length < 5)
            {
                valid = false;
                lblTeachSettWarn.ForeColor = Color.Red;
                lblTeachSettWarn.Text = "Hasło powinno posiadać co najmniej 5 znaków!";
            }
            // jeśli wszystko jest dobrze, to zapisujemy zmianę hasła
            if (valid)
            {
                String newPassword = tbTeachSettNewP.Text;
                user.Password = MD5Coder.encode(newPassword);
                userDAO.update(user);
                //
                lblTeachSettWarn.ForeColor = Color.Green;
                lblTeachSettWarn.Text = "Zmieniono hasło.";
            }

            Cursor = Cursors.Default;
        }


       
        private void button1_Click_1(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            Int32 selectedRowCount = gridPref.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (selectedRowCount > 0)
            {
                int selectedIndex = gridPref.SelectedRows[0].Index;
                Hour hour = hours.ElementAt(selectedIndex);
                TeacherDAO teacherDAO = DAOFactory.getTeacherDAO(mode);
                Teacher teacher = teacherDAO.getById(Authenticator.LogedUser.Id);
                teacher.Hours.Remove(hour);
                teacherDAO.update(teacher);
                MessageBox.Show("Usunięto preferencję.");
                fillHours();
            }
            else
            {
                MessageBox.Show("Proszę zaznaczyć wiersz z preferencją do usunięcia.");
            }

            Cursor = Cursors.Default;
        }

        // do przeniesienia
        private void buttonAddAntypref_Click(object sender, EventArgs e)
        {
            int n = gridAntypref.Rows.Add();
            gridAntypref.Rows[n].Cells[0].Value = comboBoxTeacher.SelectedItem.ToString();
            gridAntypref.Rows[n].Cells[1].Value = dtpickFrom.Value.ToString("dd-MM-yyyy HH:mm");
            gridAntypref.Rows[n].Cells[2].Value = dtpickTo.Value.ToString("dd-MM-yyyy HH:mm");
            gridAntypref.AutoResizeColumns();
            gridAntypref.AutoResizeRows();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            smScheduleForm scheduleForm = new smScheduleForm();
            scheduleForm.Show();
            Cursor = Cursors.Default;
        }
        //

        private void comboBoxGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxGroups.SelectedIndex != -1)
            {
                comboBoxClassrooms.SelectedIndex = -1;
                comboBoxTeachers.SelectedIndex = -1;
            }
        }

        private void comboBoxClassrooms_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxClassrooms.SelectedIndex != -1)
            {
                comboBoxGroups.SelectedIndex = -1;
                comboBoxTeachers.SelectedIndex = -1;
            }
        }

        private void comboBoxTeachers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxTeachers.SelectedIndex != -1)
            {
                comboBoxGroups.SelectedIndex = -1;
                comboBoxClassrooms.SelectedIndex = -1;
            }
        }

        private void buttonShowPlan_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            int selectedIndex;
            if ((selectedIndex = comboBoxGroups.SelectedIndex) != -1)
            {
                if (mode == Mode.School)
                {
                    Group group = groups.ElementAt(selectedIndex);
                    loadGroupPlan(group);
                }
                else
                {
                    Category category = categories.ElementAt(selectedIndex);
                    loadCategoryPlan(category);
                }
            }
            else if ((selectedIndex = comboBoxClassrooms.SelectedIndex) != -1)
            {
                Classroom classroom = classrooms.ElementAt(selectedIndex);
                loadClassroomPlan(classroom);
            }
            else if ((selectedIndex = comboBoxTeachers.SelectedIndex) != -1)
            {
                Teacher teacher = teachers.ElementAt(selectedIndex);
                loadTeacherPlan(teacher);
            }

            Cursor = Cursors.Default;
        }


        private void loadGroupPlan(Group g)
        {
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];
            int[,] subjectsIds = new int[numberOfRows, numberOfColumns];
            int[] subjects = new int[MAX_NUMBER_OF_SUBJECTS];
            int numberOfSubjects = 0;

            ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = scheduleDAO.getByGroup(g);
            //IList<Schedule> list = ScheduleManager.ScheduleManager.getWeeklySchedule();
            foreach (var elem in list)
            {
                //if (elem.Group.Equals(g))
                //{

                int currentSubjectId = elem.Subject.Id;
                int position = Array.IndexOf(subjects, currentSubjectId);
                if (position < 0)
                {
                    subjects[numberOfSubjects++] = currentSubjectId;
                }

                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                subjectsIds[rowNumber, columnNumber] = currentSubjectId;

                string cell = elem.Subject.Name + "\n" + elem.Teacher.Name + "\n" + elem.Classroom.Name;
                cells[rowNumber, columnNumber] = cell;
                //}

            }

            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                    {
                        int colorPosition = Array.IndexOf(subjects, subjectsIds[r, b]);
                        grid.Rows[r].Cells[b].Style.BackColor = colors[colorPosition];
                    }
                }
                //

            }

            autoResize();

        }

        private void loadCategoryPlan(Category category)
        {
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];
            int[,] subjectsIds = new int[numberOfRows, numberOfColumns];
            int[] subjects = new int[MAX_NUMBER_OF_SUBJECTS];
            int numberOfSubjects = 0;

            ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = scheduleDAO.getAll();
            //IList<Schedule> list = ScheduleManager.ScheduleManager.getWeeklySchedule();
            foreach (var elem in list)
            {
                if (elem.Subject.Category.Id == category.Id)
                {

                    int currentSubjectId = elem.Subject.Id;
                    int position = Array.IndexOf(subjects, currentSubjectId);
                    if (position < 0)
                    {
                        subjects[numberOfSubjects++] = currentSubjectId;
                    }

                    ClassHour classHour = elem.ClassHour;
                    int rowNumber = classHours.IndexOf(classHour);
                    DB.Domain.Core.Day day = elem.Day;
                    int columnNumber = days.IndexOf(day);

                    subjectsIds[rowNumber, columnNumber] = currentSubjectId;

                    string cell = elem.Subject.Name + "\n" + elem.Teacher.Name;
                    cells[rowNumber, columnNumber] = cell;

                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                            subjectsIds[rowNumber + time, columnNumber] = currentSubjectId;
                        }
                    }

                }

            }

            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                    {
                        int colorPosition = Array.IndexOf(subjects, subjectsIds[r, b]);
                        grid.Rows[r].Cells[b].Style.BackColor = colors[colorPosition];
                    }
                }
                //

            }

            autoResize();

        }


        private void loadClassroomPlan(Classroom cr)
        {
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];

            ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = scheduleDAO.getByClassroom(cr);
            //IList<Schedule> list = ScheduleManager.ScheduleManager.getWeeklySchedule();
            foreach (var elem in list)
            {
                //if (elem.Classroom.Equals(cr))
                //{
                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                string cell;
                if (mode == Mode.School)
                {
                    cell = elem.Subject.Name + "\n" + elem.Teacher.Name + "\n" + elem.Group.Name;
                }
                else
                {
                    cell = elem.Subject.Name + "\n" + elem.Teacher.Name;
                }
                cells[rowNumber, columnNumber] = cell;

                if (mode == Mode.University)
                {
                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                        }
                    }
                }
                //}

            }

            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                        grid.Rows[r].Cells[b].Style.BackColor = Color.LightBlue;
                }
                //

            }

            autoResize();

        }


        private void loadTeacherPlan(Teacher t)
        {
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];

            ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = scheduleDAO.getByTeacher(t);
            //IList<Schedule> list = ScheduleManager.ScheduleManager.getWeeklySchedule();
            foreach (var elem in list)
            {
                //if (elem.Teacher.Equals(t)) {

                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                string cell;
                if (mode == Mode.School)
                {
                    cell = elem.Subject.Name + "\n" + elem.Classroom.Name + "\n" + elem.Group.Name;
                }
                else
                {
                    cell = elem.Subject.Name + "\n" + elem.Classroom.Name;
                }
                cells[rowNumber, columnNumber] = cell;

                if (mode == Mode.University)
                {
                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                        }
                    }
                }



                //}

            }

            // Sprawdzenie harmonogramu awaryjnego.
            //TimeSpan now = TimeSpan.FromTicks( DateTime.Now.Ticks );
            //MessageBox.Show(now.ToString());
            //EmergencyScheduleDAO emergencyScheduleDAO = DAOFactory.getEmergencyScheduleDAO(mode);
            //IList<EmergencySchedule> emergencyScheduleList = emergencyScheduleDAO.getByTeacher(t);
            //foreach(var emergencyScheduleElement in emergencyScheduleList)
            //{
            //emergencyScheduleElement.Date;
            //}

            // Wpisanie do grida.
            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                        grid.Rows[r].Cells[b].Style.BackColor = Color.LightBlue;
                }
                //

            }

            autoResize();

        }



        private void autoResize()
        {
            grid.AutoResizeColumns();
            grid.AutoResizeRows();
        }
        
    }
}